import { sysLoginAPI, sysProfileAPI, sysUserAPI } from '@/api'
// import { getToken, setToken } from '@/utils/auth'
// 导入动态路由
import { syncRouter } from '@/router/index.js'
import { constantRoutes } from '@/router/index.js'
import { resetRouter } from '@/router/index.js'
//  导入路由
import router from '@/router/index.js'
const state = {
  token: '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    // 把token 存入vuex
    state.token = value
  },
  setUseInfo(state, value) {
    state.userInfo = value
  },
  logOut(state, value) {
    state.token = ''
    state.userInfo = ''
    resetRouter()
  }
}

const actions = {
  async getToken(store, value) {
    const res = await sysLoginAPI(value)
    store.commit('setToken', res.data)
  },
  async getUseInfo(store) {
    const res = await sysProfileAPI()
    store.commit('setUseInfo', res.data)
    const res2 = await sysUserAPI(res.data.userId)
    const info = Object.assign({}, res.data, res2.data)
    store.commit('setUseInfo', info)
    const newArr = syncRouter.filter((item) => {
      return info.roles.menus.includes(item.meta.name)
    })
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    router.addRoutes(newArr)
    store.commit('routes/setRoutes', [...constantRoutes, ...newArr], {
      root: true
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
